package com.lovo.ssc.service.impl;

import com.lovo.ssc.entity.Customer;
import com.lovo.ssc.entity.Ordergoods;
import com.lovo.ssc.entity.SysOrder;
import com.lovo.ssc.service.IOrdergoodsService;
import com.lovo.ssc.service.ISysOrderService;
import com.lovo.sscweb.dto.OrderDto;
import com.lovo.sscweb.dto.OrderItemTo;
import com.lovo.util.MQUtil;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class OrderMQService {

    @Autowired
    ISysOrderService orderService;
    @Autowired
    IOrdergoodsService goodsService;

    @RabbitListener(queues = MQUtil.PrepayOrderQueue)
    public void order(Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag, OrderDto dto)throws Exception{
//        System.out.println(dto);
        if (dto!=null){
            Customer customer = orderService.findByUserName(dto.getUsername());
            SysOrder order = new SysOrder();
            order.setCustomerid(customer.getCustomerid());
            order.setCode(dto.getOrderCode());
            order.setOrderstate("已完成");
            order.setAddress(dto.getShippingAddress());
            double d = dto.getPayPrice();
            float f = (float)d;
            order.setMoney(f);
            order.setTime(dto.getPlaOrderTime());
            order.setType(dto.getOrderType());
            int id = orderService.addOrder(order);
            List<OrderItemTo> list = dto.getGoodsList();
            Ordergoods goods = new Ordergoods();
            for (int i=0;i<list.size();i++){
                goods.setOrderid(id);
                List batchList = list.get(i).getGoodsBatch();
                goods.setBatch(batchList.get(0).toString());
                goods.setSpecs(list.get(i).getNorms());
                goods.setGoodsname(list.get(i).getGoodsName());
                goods.setNum(list.get(i).getBuyNum());
                goods.setPrice(list.get(i).getGoodsPrice());
                goods.setType(list.get(i).getGoodsType());
                goodsService.save(goods);
            }
        }
        channel.basicAck(tag,false); //false不进行批量确认
    }
}
